package com.parkinglot.management.service.impl;

import com.parkinglot.management.repository.EnteredCarInfoRepository;
import com.parkinglot.management.repository.OrderRepository;
import com.parkinglot.management.repository.entity.EnteredCarInfo;
import com.parkinglot.management.repository.entity.Order;
import com.parkinglot.management.service.OrderService;
import com.parkinglot.management.util.DiscernCarNum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderRepository orderRepository;
    @Autowired
    EnteredCarInfoRepository enteredCarInfoRepository;
    @Autowired
    DiscernCarNum discernCarNum;

    private  final SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

    @Override
    public List<Order> getAllOrders() {
        return orderRepository.findAll();
    }

    @Override
    public Order addOrder(String path, String leavedTime) throws ParseException {
        String carNum = discernCarNum.getCarNumFromImg(path);
        EnteredCarInfo enteredCarInfo = enteredCarInfoRepository.findEnteredCarInfoByCarNum(carNum);
        if (!Objects.isNull(enteredCarInfo)) {
            String enteredTime = enteredCarInfo.getEnterTime();
            long stayedTime = df.parse(leavedTime).getTime() - df.parse(enteredTime).getTime();
            stayedTime = stayedTime/(60*60*1000);
            BigDecimal cost = new BigDecimal(stayedTime * 10);
            Order order = new Order();
            order.setCarNum(carNum);
            order.setEnterTime(enteredTime);
            order.setLeaveTime(leavedTime);
            order.setCost(cost);
            order.setStatus(false);
            Order saved = orderRepository.save(order);
            return saved;
        } else {
            return null;
        }

    }

    @Override
    public List<Order> getOrderByNum(String carNumber) {
        return orderRepository.findAllByCarNum(carNumber);
    }

    @Override
    public void deleteOrder(Order order) {
        orderRepository.delete(order);
    }
}
